package com.blb.controller;

import com.blb.pojo.Employee;
import com.blb.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("findAllEmployees")
    public String findAll(Model model){
        List<Employee> employees = employeeService.findAll();
        model.addAttribute("employees",employees);
        return "employee";
    }

    @RequestMapping("findEmployeesLikeName")
    public String findEmployeesLikeName(@RequestParam(required = false,defaultValue = "") String name, Model model){
        List<Employee> employees = employeeService.findEmployeesLikeName(name);
        model.addAttribute("employees",employees);
        return "employee";
    }

    @RequestMapping("findEmployeeById")
    public String findEmployeeById(Long id,Model model){
        Employee employee = employeeService.findById(id);
        model.addAttribute("employee",employee);
        return "emp";
    }

    //404 路径错 ,400 参数错 401 访问非法 403 权限 405 方法错
    @RequestMapping("updateEmployee")
    public String updateEmployee(Employee employee, MultipartFile image1) throws IOException {
        //获得项目的相对路径保存文件
        String path = "D:/upload-images";
        File file = new File(path);
        //不存在就创建目录
        if(!file.exists()){
            file.mkdirs();
        }
        //将后缀名截取出来，将名字设置为uuid
        int index = image1.getOriginalFilename().lastIndexOf(".");
        String extension = image1.getOriginalFilename().substring(index);
        String filename = UUID.randomUUID().toString().replace("-", "");
        filename = filename + extension;
        //将文件保存到磁盘上
        image1.transferTo(new File(file.getAbsolutePath() + "\\" + filename));
        employee.setImage(filename);
        employeeService.updateEmployee(employee);
        return "redirect:findAllEmployees";
    }
}
